package com.sunther.document.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunther.document.Enum.DictEnum;
import com.sunther.document.dao.FileSystemDao;
import com.sunther.document.entity.*;
import com.sunther.document.service.FileService;
import com.sunther.document.service.FileSystemMidService;
import com.sunther.document.service.FileSystemService;
import com.sunther.document.service.ProjectService;
import com.sunther.document.util.UserInfoUtil;
import com.sunther.idb.common.util.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author csb
 * @description: TODO
 * @date 2023/5/17 16:15
 */
@Service
public class FileSystemServiceImpl extends ServiceImpl<FileSystemDao, FileSystemEntity> implements FileSystemService {

    @Autowired
    private FileSystemMidService fileSystemMidService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private FileService fileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WebResult saveData(FileSystemMidEntity data, HttpServletRequest request) {

        Integer userId = UserInfoUtil.getUserId(request);

        if (data.getSystemType().equals(DictEnum.SYSTEM_TYPE_TEMPLATE.getCode())){
            QueryWrapper<FileSystemMidEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("name",data.getName());
            if (null != data.getId()){
                wrapper.ne("id",data.getId());
            }
            long count = fileSystemMidService.count(wrapper);
            if (count > 0) {
                return WebResult.failure("该模板名称已存在");
            }
        }

        List<FileSystemEntity> systems = data.getTreeList();
        if (data.getId() == null){
            data.init(String.valueOf(userId));
            String uuid = IdUtil.simpleUUID();
            data.setId(uuid);
        }else {
            data.modify(String.valueOf(userId));
        }
        systems.stream().forEach(a -> { a.setMidId(data.getId()); });

        HashMap<String, List<FileSystemEntity>> map = getSystemEntityData(systems,userId);
        List<FileSystemEntity> save = map.get("save");
        List<FileSystemEntity> update = map.get("update");

        fileSystemMidService.saveOrUpdate(data);

        saveBatch(save);
        updateBatchById(update);

        return WebResult.success("操作成功",data);
    }

    @Override
    public FileSystemEntityVo detail(String id) {
        FileSystemMidEntity midEntity = fileSystemMidService.getById(id);

        QueryWrapper<FileSystemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mid_id",midEntity.getId());
        List<FileSystemEntity> systemEntityList = list(wrapper);
        List<Tree<String>> trees = FileSystemEntity.getTrees(systemEntityList);

        FileSystemEntityVo vo = new FileSystemEntityVo();
        vo.setId(midEntity.getId());
        vo.setName(midEntity.getName());
        vo.setSystemType(midEntity.getSystemType());
        vo.setTreeList(trees);

        return vo;
    }

    @Override
    public WebResult delDetail(String id) {

        QueryWrapper<FileSystemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        long count = count(wrapper);
        if (count > 0) {
            return WebResult.failure("禁止删除，请先清除子目录");
        }

        //todo 判断是否有文件
        QueryWrapper<FileEntity> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("system_id",id);
        long count1 = fileService.count(wrapper2);
        if (count1 > 0) {
            return WebResult.failure("禁止删除，请先删除该目录底下的文件");
        }

        removeById(id);
        return WebResult.success("操作成功");
    }

    @Override
    public WebResult projectByDtl(String projectId, HttpServletRequest request) {

        Integer roleId = UserInfoUtil.getRoleId(request);
        Integer userId = UserInfoUtil.getUserId(request);

        ProjectEntity projectEntity = projectService.getById(projectId);
        FileSystemMidEntity midEntity = fileSystemMidService.getById(projectEntity.getSystemId());
        QueryWrapper<FileSystemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mid_id",midEntity.getId());
        List<FileSystemEntity> systemEntityList = list(wrapper);

        List<Tree<String>> trees = FileSystemEntity.getTrees(systemEntityList);

        HashMap<String, Object> map = new HashMap<>();
        long count = fileService.getCountByProjectId(projectId, roleId, userId);
        map.put("count",count);

        return WebResult.success("操作成功",trees,map);
    }

    @Override
    public Map<String, String> getSystemNameMap() {
        List<FileSystemEntity> list = list();
        Map<String, String> map = list.stream().collect(Collectors.toMap(FileSystemEntity::getId, FileSystemEntity::getName));
        return map;
    }

    public HashMap<String, List<FileSystemEntity>> getSystemEntityData(List<FileSystemEntity> systems, Integer userId){
        ArrayList<FileSystemEntity> saves = new ArrayList<>();
        ArrayList<FileSystemEntity> updates = new ArrayList<>();
        systems.stream().forEach(a -> {
            ArrayList<FileSystemEntity> saveList = new ArrayList<>();
            ArrayList<FileSystemEntity> updateList = new ArrayList<>();
            recursionTree(a, "0", a.getMidId(), saveList, updateList, userId);
            saves.addAll(saveList);
            updates.addAll(updateList);
        });

        HashMap<String, List<FileSystemEntity>> map = new HashMap<>();
        map.put("save",saves);
        map.put("update",updates);
        return map;
    }

    /**
     * 递归目录树
     */
    public void recursionTree(FileSystemEntity data, String id, String midId, ArrayList<FileSystemEntity> saveList, ArrayList<FileSystemEntity> updateList, Integer userId) {
        data.setParentId(id);
        data.setMidId(midId);
        if (StrUtil.isBlank(data.getId())){
            String uuid = IdUtil.simpleUUID();
            data.setId(uuid);
            data.init(String.valueOf(userId));
            saveList.add(data);
        }else {
            data.modify(String.valueOf(userId));
            updateList.add(data);
        }

        List<FileSystemEntity> children = data.getChildren();
        if (children != null && children.size() > 0) {
            children.stream().forEach(a -> {
                recursionTree(a, data.getId(), data.getMidId(), saveList, updateList, userId);
            });
        }
    }
}
